<template>
  <section class="w-full bg-gradient-to-b from-indigo-50/60 to-white">
    <div class="max-w-[1200px] mx-auto px-4 lg:px-8 py-10 lg:py-14 text-center">
      <h1 class="text-2xl lg:text-3xl font-semibold text-gray-900 tracking-tight">发现你的AI伙伴</h1>
      <p class="mt-2 text-gray-500">探索数千个独特的AI角色，找到最合你心意的灵魂角色</p>

      <div class="mt-6 flex items-center max-w-2xl mx-auto bg-white rounded-xl shadow-sm ring-1 ring-gray-200 overflow-hidden">
        <div class="pl-4 text-gray-400">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-4.35-4.35m0 0A7.5 7.5 0 103.5 3.5a7.5 7.5 0 0013.15 13.15z"/>
          </svg>
        </div>
        <input 
          ref="searchInput"
          v-model="searchKeyword"
          class="flex-1 h-12 px-3 outline-none placeholder:text-gray-400 text-gray-700" 
          placeholder="输入关键词搜索角色..." 
          @keyup.enter="handleSearch"
        />
        <button 
          class="h-10 mr-2 px-4 rounded-lg bg-[#635BFF] text-white text-sm hover:opacity-90 transition"
          @click="handleSearch"
        >
          搜索
        </button>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const searchInput = ref<HTMLInputElement>()
const searchKeyword = ref('')

// 自动聚焦搜索框
onMounted(async () => {
  await nextTick()
  
  // 从URL参数中获取搜索关键词
  const urlParams = new URLSearchParams(window.location.search)
  const keyword = urlParams.get('keyword')
  if (keyword) {
    searchKeyword.value = keyword
  }
  
  if (searchInput.value) {
    searchInput.value.focus()
  }
})

// 处理搜索
const handleSearch = () => {
  // 更新URL参数，触发RoleGrid重新搜索
  const currentQuery = { ...route.query }
  
  if (searchKeyword.value.trim()) {
    // 有搜索词时，添加到URL参数
    currentQuery.keyword = searchKeyword.value.trim()
  } else {
    // 清空搜索时，移除keyword参数
    delete currentQuery.keyword
  }
  
  // 构建新的URL
  const newUrl = Object.keys(currentQuery).length > 0 
    ? `${route.path}?${new URLSearchParams(currentQuery as any).toString()}`
    : route.path
  
  // 使用replace避免历史记录堆积
  window.history.replaceState({}, '', newUrl)
  
  // 触发搜索事件，让RoleGrid组件重新获取数据
  window.dispatchEvent(new CustomEvent('search-updated', { 
    detail: { keyword: searchKeyword.value.trim() } 
  }))
}
</script>


